<!DOCTYPE html>

<html lang="zh-CN">

<head>

    <meta charset="UTF-8">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, target-densityDpi=device-dpi" />
    <!-- 微软的老式浏览器 -->
    <meta name="MobileOptimized" content="320">
    <!-- 启用360浏览器的极速模式(webkit) – -->
    <meta name="renderer" content="webkit">
    <!-- 避免IE使用兼容模式 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- 针对手持设备优化，主要是针对一些老的不识别viewport的浏览器，比如黑莓 -->
    <meta name="HandheldFriendly" content="true">
    <!-- uc强制竖屏 -->
    <meta name="screen-orientation" content="portrait">
    <!-- QQ强制竖屏 -->
    <meta name="x5-orientation" content="portrait">
    <!-- UC强制全屏 -->
    <meta name="full-screen" content="yes">
    <!-- QQ强制全屏 -->
    <meta name="x5-fullscreen" content="true">
    <!-- UC应用模式 若开启长按无法复制链接-->
    <!--meta name="browsermode" content="application"-->
    <!-- QQ应用模式 -->
    <meta name="x5-page-mode" content="app">
    <!--网站开启对web app程序的支持-->
    <meta name="apple-touch-fullscreen" content="yes">
    <!--在web app应用下状态条（屏幕顶部条）的颜色-->
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <!-- windows phone 点击无高光 -->
    <meta name="msapplication-tap-highlight" content="no">
    <!--移动web页面是否自动探测电话号码-->
    <!--<meta http-equiv="x-rim-auto-match" content="none">-->
    <!--手机号码显示为拨号链接-->
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="Cache-Control" content="max-age=300" />
    <meta http-equiv="Expires" content="300" />

    <title>{$page_title}</title>
    <link type="text/css" href="__PUBLIC__css/reset.css" rel="stylesheet">
    <link type="text/css" href="__PUBLIC__im/css/bootstrap.css" rel="stylesheet">
    <link type="text/css" href="__PUBLIC__im/css/example.css" rel="stylesheet">
    <link type="text/css" href="__PUBLIC__im/css/message.css" rel="stylesheet">
    <!-- <link type="text/css" href="__PUBLIC__im/css/font-awesome.css" rel="stylesheet"> -->
    <script src="__PUBLIC__js/jquery.min.js"></script>
    <script src="__PUBLIC__layer_m/layer.js"></script>
    <script src="__PUBLIC__js/common.js"></script>
    <script src="__PUBLIC__js/md5.js"></script>

    <style>

        #facebox{

            position: absolute !important;

            z-index: 1000 !important;

            left: 0 !important;

            right: 0 !important;

            top: -192px !important;

            background: #e6e6e6 !important;

            border:1px solid #efefef;

        }

    </style>

</head> 

<body ng-app="sdkApp" ng-controller="sdkController">

<div class="container">

    <div class="row messageBody" style="height: auto">

        <div class="col-md-3 messageBox" style="background: none;">

            <div class="row ">

                <div class="col-md-12 msg-content" style="margin-bottom:100px;"></div>


                <div class="clearfix fixed-bottom padding" style="background: #f4f4f6;">
                    <div class="margin-small-right pull-left">

                             <span class="btn-expression">

                                 <a  href="javascript:void(0)" id="btnExpressionId" class="emotion" title="表情"></a>

                             </span>

                        </div>
                    <div class="pull-left send-btn-file">

                     <span class="send-btn-file-picture">

                       <a  href="javascript:void(0)" title="图片" class="fa fa-photo text-large">
                           
                       </a>

                     </span>

                    </div>

                    <div class="pull-right clearfix">

                        <div class="btn-box pull-left">

                            <span  id="send">发送</span><br/>

                        </div>

                    </div>

                    <div class="send-content border-bottom" id="send-content" style="overflow-y: scroll" contenteditable="true">

                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-9 detailBox" style="display: none;">



        </div>

    </div>

</div>

</body>

<script type="text/javascript" src="__PUBLIC__im/js/jquery-1.8.3.js"></script>

<script type="text/javascript" src="__PUBLIC__im/js/layer.m.js"></script>

<script src="http://res.websdk.rongcloud.cn/RongIMClient-0.9.12.min.js"></script>

<script src="http://res.websdk.rongcloud.cn/RongIMClient.emoji-0.9.2.min.js"></script>

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

<script src="__PUBLIC__im/js/jquery.qqFace.js"></script>

<script src="/Home/Im/wx_js"></script>

<script>

RongIMClient.init("{$rong_key}");

var to = {id:"{$to_info.group_id}"};

var owner = {id:"{$owner_info.id}",portrait: '{$owner_info.url_img}',name:'{$owner_info.nickname}',
            token:'{$owner_info.rong_token}'};

var unread_num = 0;

var myUtil = {

        msgType: function (message) {

            switch (message.getMessageType()) {

                case RongIMClient.MessageType.TextMessage:

                    //return String.stringFormat('<div class="msgBody">{0}</div>', this.initEmotion(this.symbolReplace(message.getContent())));

                    return String.stringFormat('<div class="msgBody">{0}</div>', replace_em(message.getContent()));

                case RongIMClient.MessageType.ImageMessage:

                    return String.stringFormat('<div class="msgBody">{0}</div>', "<img class='imgThumbnail' src='data:image/jpg;base64," + message.getContent() + "' bigUrl='" + message.getImageUri() + "' onclick='popBigPic(this)'/>");

                case RongIMClient.MessageType.VoiceMessage:

                    return String.stringFormat('<div class="msgBody voice">{0}</div><input type="hidden" value="' + message.getContent() + '">', "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + message.getDuration());

                case RongIMClient.MessageType.LocationMessage:

                    return String.stringFormat('<div class="msgBody">{0}</div>{1}', "[位置消息]" + message.getPoi(), "<img src='data:image/png;base64," + message.getContent() + "' onclick='popBigPic(this)'/>");

                case RongIMClient.MessageType.RichContentMessage:

                    return '<div class="msgBody">'+replace_em(message.getContent())+'</div>'

                default :

                    return '<div class="msgBody">' + message.getMessageType().toString() + ':此消息类型Demo未解析</div>'

            }

        },

        msgHistory: function (message) {

            return String.stringFormat('<div class="msgBody">{0}</div>', replace_em(message));

        },

        initEmotion: function (str) {

            var a = document.createElement("span");

            return RongIMClient.Expression.retrievalEmoji(str, function (img) {

                a.appendChild(img.img);

                var str = '<span class="RongIMexpression_' + img.englishName + '">' + a.innerHTML + '</span>';

                a.innerHTML = "";

                return str;

            });

        },

        symbolReplace: function (str) {

            if (!str) return '';

            str = str.replace(/&/g, '&amp;');

            str = str.replace(/</g, '&lt;');

            str = str.replace(/>/g, '&gt;');

            str = str.replace(/"/g, '&quot;');

            str = str.replace(/'/g, '&#039;');

            return str;

        },

        replaceSymbol: function (str) {

            if (!str) return '';

            str = str.replace(/&amp;/g, '&');

            str = str.replace(/&lt;/g, '<');

            str = str.replace(/&gt;/g, '>');

            str = str.replace(/&quot;/g, '"');

            str = str.replace(/&#039;/g, "'");

            str = str.replace(/&nbsp;/g, " ");

            return str;

        }

    },historyStr = '<div class="xiaoxiti {0} user"><p>{6}</p>' +

                        '<div class="user_img"><img onerror="this.src=/App/Home/Public/images/personPhoto.png" src="{1}" /></div><span>{2}</span>' +

                   '<div class="msg">' +

                        '<div class="msgArrow"><img src="__PUBLIC__images/{3}"></div><span></span>{4}</div>' +

                   '<div messageId="{5}" class="status"></div>' +

                   '</div>' +

                   '<div class="slice"></div>',base64Str="";



console.log('开始链接');

RongIMClient.setConnectionStatusListener({
 
    onChanged: function (status) {

        console.log(status);

        switch (status) {

            //链接成功

            case RongIMClient.ConnectionStatus.CONNECTED:

                console.log('链接成功');

                break;

            //正在链接

            case RongIMClient.ConnectionStatus.CONNECTING:

                console.log('正在链接');

                break;

            //重新链接

            case RongIMClient.ConnectionStatus.RECONNECT:

                console.log('重新链接');

                break;

            //其他设备登陆

            case RongIMClient.ConnectionStatus.OTHER_DEVICE_LOGIN:

            //连接关闭

            case RongIMClient.ConnectionStatus.CLOSURE:

            //未知错误

            case RongIMClient.ConnectionStatus.UNKNOWN_ERROR:

            //登出

            case RongIMClient.ConnectionStatus.LOGOUT:

            //用户已被封禁

            case RongIMClient.ConnectionStatus.BLOCK:

                break;

        }



    }

});

// 消息监听器

RongIMClient.getInstance().setOnReceiveMessageListener({

    // 接收到的消息

    onReceived: function (message) {

        console.log(message);

    

        if(message.getTargetId() == to.id){

            RongIMClient.getInstance().getUserInfo(message.getSenderUserId(),{

                onSuccess:function(info){

                    console.log(info);
                    console.log(info.getUserId());

                    addHistoryMessages(message,info);

                //成功 info instanceOf RongIMClient.UserInfo

                },onError:function(){

                    console.log("失败");

                //失败

                }

            })

        }else{

            /*var count = RongIMClient.getInstance().getUnreadCount(message.getConversationType(),message.getTargetId())

            $('#friendlistId').find('li').each(function(index,item){

                if(item.innerHTML.indexOf(message.getTargetId())>-1){

                   $(item).find('span')[3].innerHTML= count>4?'5+':count;

                   $($(item).find('span')[3]).show();

                }

            });*/

        }

        switch (message.getMessageType()) {

            case RongIMClient.MessageType.TextMessage:

                console.log('TextMessage');

                break;

            case RongIMClient.MessageType.ImageMessage:

                console.log('ImageMessage');

                break;

            case RongIMClient.MessageType.VoiceMessage:

                console.log('VoiceMessage');

                break;

            case RongIMClient.MessageType.RichContentMessage:

                console.log('RichContentMessage');

                break;

            case RongIMClient.MessageType.LocationMessage:

                console.log('LocationMessage');

                break;

            case RongIMClient.MessageType.DiscussionNotificationMessage:

                console.log('DiscussionNotificationMessage');

                break;

            case RongIMClient.MessageType.InformationNotificationMessage:

                console.log('InfomationNotificationMessage');

                break;

            case RongIMClient.MessageType.ContactNotificationMessage:

                console.log('ContactNotificationMessage');

                break;

            case RongIMClient.MessageType.ProfileNotificationMessage:

                console.log('ProfileNotificationMessage');

                break;

            case RongIMClient.MessageType.CommandNotificationMessage:

                console.log('CommandNotificationMessage');

                break;

            case RongIMClient.MessageType.UnknownMessage:

                console.log('UnknownMessage');

                break;

            default:

            // 自定义消息

            // do something...

        }

    }

});



RongIMClient.connect(owner.token, {

    onSuccess: function (userId) {

        // 此处处理连接成功。

        console.log("Login successfully." + userId);

        getHistory(to.id,4);

        unread_num = RongIMClient.getInstance().getTotalUnreadCount(RongIMClient.ConversationType.GROUP,to.id);

    },

    onError: function (errorCode) {

        // 此处处理连接错误。

        var info = '';

        switch (errorCode) {

            case RongIMClient.callback.ErrorCode.TIMEOUT:

                info = '超时';

                break;

            case RongIMClient.callback.ErrorCode.UNKNOWN_ERROR:

                info = '未知错误';

                break;

            case RongIMClient.ConnectErrorStatus.UNACCEPTABLE_PROTOCOL_VERSION:

                info = '不可接受的协议版本';

                break;

            case RongIMClient.ConnectErrorStatus.IDENTIFIER_REJECTED:

                info = 'appkey不正确';

                break;

            case RongIMClient.ConnectErrorStatus.SERVER_UNAVAILABLE:

                info = '服务器不可用';

                break;

            case RongIMClient.ConnectErrorStatus.TOKEN_INCORRECT:

                info = 'token无效';

                break;

            case RongIMClient.ConnectErrorStatus.NOT_AUTHORIZED:

                info = '未认证';

                break;

            case RongIMClient.ConnectErrorStatus.REDIRECT:

                info = '重新获取导航';

                break;

            case RongIMClient.ConnectErrorStatus.PACKAGE_ERROR:

                info = '包名错误';

                break;

            case RongIMClient.ConnectErrorStatus.APP_BLOCK_OR_DELETE:

                info = '应用已被封禁或已被删除';

                break;

            case RongIMClient.ConnectErrorStatus.BLOCK:

                info = '用户被封禁';

                break;

            case RongIMClient.ConnectErrorStatus.TOKEN_EXPIRE:

                info = 'token已过期';

                break;

            case RongIMClient.ConnectErrorStatus.DEVICE_ERROR:

                info = '设备号错误';

                break;

        }

        console.log("失败:" + info);

    }

});



$(function(){
	$('#send-content').click(function() {
        $('.fixed-bottom').css('padding','0.2rem 0.4266666666667rem 1.2rem 0.4266666666667rem')
        $('.fixed-bottom').css('bottom','0');
        document.addEventListener("touchmove",function(e){
          e.preventDefault();
          e.stopPropagation();
      },false);
    });
    $('#send-content').blur(function() {
        $('.fixed-bottom').css('bottom','0');
        $('.fixed-bottom').css('padding','0.2rem 0.4266666666667rem 0.2rem 0.4266666666667rem')
        document.addEventListener("touchmove",function(e){
           e.returnValue = true;
      },false);
    });
    $("#send").bind('click', function () {
        var user_rename = "{$_SESSION['user']['card_status']}"
        if(user_rename==0){
              layer.open({
                    content: '您未进行实名认证该消息发送不成功是否立即实名？'
                    ,btn: ['实名认证', '再逛逛']
                    ,yes: function(index){
                      location.href='/Home/Person/relaname';
                      layer.close(index);
                    }
                  });
              return;
        }
        //console.log(user_rename);return;
        if ($('.send-content').html() == "") {

            layer.open({
                    content: '发送内容不能为空!'
                    , skin: 'msg'
                    , time: 1
                    
                });

            return;

        }
        if(!to.id){

            layer.open({
                    content: '请选择聊天对象!'
                    , skin: 'msg'
                    , time: 1
                    
                });

            return;

        }

        var strs = replace_img($(".send-content").html());

        var con = strs.replace(/\[.+?\]/g, function (x) {

            return RongIMClient.Expression.getEmojiObjByEnglishNameOrChineseName(x.slice(1, x.length - 1)).tag || x;

        }),msg=null;

        if($('#pictureuploadId').val()!=""){

            //msg = RongIMClient.RichContentMessage.obtain('test',con,base64Str);
			msg = RongIMClient.TextMessage.obtain(con);

        }

        else{

            msg = RongIMClient.TextMessage.obtain(con);

        }

        var conversationtype = RongIMClient.ConversationType.GROUP;

        var content = $('#pictureuploadId').val()!=""?new RongIMClient.MessageContent(RongIMClient.RichContentMessage.obtain("test",myUtil.replaceSymbol(con),base64Str)):

        new RongIMClient.MessageContent(RongIMClient.TextMessage.obtain(myUtil.replaceSymbol(con))); 

        

        //var msg = new RongIMClient.TextMessage();

        // 设置消息内容

        //msg.setContent(strs);

        //或者使用RongIMClient.TextMessage.obtain方法.具体使用请参见文档

        //var msg = RongIMClient.TextMessage.obtain(strs);

        //var conversationtype = RongIMClient.ConversationType.PRIVATE; // 私聊

        

        //var content = $('#pictureuploadId').val()!=""?new RongIMClient.MessageContent(RongIMClient.RichContentMessage.obtain("test",myUtil.replaceSymbol(con),base64Str)):

        //new RongIMClient.MessageContent(RongIMClient.TextMessage.obtain(myUtil.replaceSymbol(con)));

        console.log(msg.getContent()+to.id);

        

        RongIMClient.getInstance().sendMessage(RongIMClient.ConversationType.GROUP, to.id, msg, null, {

                // 发送消息成功

                onSuccess: function () {

                    console.log("Send successfully");

                    addHistoryMessages(content.getMessage(),owner);

                    $.post("/Home/Im/add_messages",{

                        send_uin:owner.id,

                        group_id:to.id,

                        content:msg.getContent(),

                    },function(data){
                     
                        //console.log(data);

                    });

                },

                onError: function (errorCode) {

                    var info = '';

                    switch (errorCode) {

                        case RongIMClient.callback.ErrorCode.TIMEOUT:

                            info = '超时';

                            break;

                        case RongIMClient.callback.ErrorCode.UNKNOWN_ERROR:

                            info = '未知错误';

                            break;

                        case RongIMClient.SendErrorStatus.REJECTED_BY_BLACKLIST:

                            info = '在黑名单中，无法向对方发送消息';

                            break;

                        case RongIMClient.SendErrorStatus.NOT_IN_DISCUSSION:

                            info = '不在讨论组中';

                            break;

                        case RongIMClient.SendErrorStatus.NOT_IN_GROUP:

                            info = '不在群组中';

                            break;

                        case RongIMClient.SendErrorStatus.NOT_IN_CHATROOM:

                            info = '不在聊天室中';

                            break;

                        default :

                            info = x;

                            break;

                    }

                    console.log('发送失败:' + info);

                }

            }

        );

        //document.body.scrollTop=document.body.scrollHeight;



        $('.send-content').html('');

    });

    $('.emotion').qqFace({

        id : 'facebox', //表情盒子的ID

        assign:'send-content', //给那个控件赋值

        path:'__PUBLIC__/im/face/'  //表情存放的路径

    });

    

    $("#btnExpressionId").click(function(){

        //$("#QQFace").toggle();

    });





    get_History(0,unread_num);

    //var currScroll=$(document).scrollTop();

    $(document).scroll(function(){

        if($(document).scrollTop()==0){

            first_id = $(".xiaoxiti").first().find(".status").attr("messageid");

            console.log(first_id);

            get_History(first_id,0)

        }

    });

});







function addHistoryMessages(item,info) {
    console.log(item)
    $(".msg-content").append(String.stringFormat(historyStr,

        item.getMessageDirection() == RongIMClient.MessageDirection.RECEIVE ? "other_user" : "self",

        item.getMessageDirection() == RongIMClient.MessageDirection.RECEIVE ? info.getPortraitUri() : owner.portrait,

        "",

        item.getMessageDirection() == RongIMClient.MessageDirection.RECEIVE ? 'white_arrow.png' : 'blue_arrow.png',

        myUtil.msgType(item),

        item.getMessageId(),

        item.getMessageDirection() == RongIMClient.MessageDirection.RECEIVE ? info.getUserName() : owner.name

        ));

    if($("body").height()+60>$(window).height()){

        //$("html,body").animate({scrollTop:$("body").height()-$(window).height()+'px'},1000);

        $("html,body").scrollTop($(document).height()-$(window).height())

        console.log($("html,body").scrollTop());

    }

        

}

//加载历史记录

function getHistory(id, type) {  

    RongIMClient.getInstance().getHistoryMessages(RongIMClient.ConversationType.GROUP,to.id,20,{

        onSuccess: function (has, list) {

            console.log("是否有剩余消息：" + has);

            //list.forEach(function(item){

            //  addHistoryMessages(item);

            //});

        }, onError: function () {

            console.log('获取历史消息失败');

        }

    });

}

function get_History(id,num) {

    var old_height = $(document).height();

    $.post("/Home/Im/get_group_messages",{

        id:id,

        group_id:"{$group_id}",

        num:num,

    },function(data){

        var html = "";

        $(data).each(function(index,element){
            html = String.stringFormat(historyStr,

            element.send_id == owner.id ? "self" : "other_user",

            element.receive_id == owner.id ? owner.portrait : element.portraituri,

            "",

            element.send_id == owner.id ? 'blue_arrow.png' : 'white_arrow.png',

            myUtil.msgHistory(element.content), 

            element.id,

            element.receive_id == owner.id ? owner.name : element.name

            ) + html;

            

        });

        $(".msg-content").html(html+$(".msg-content").html());

        var new_height = $(document).height();

        $(document).scrollTop(new_height - old_height);

        console.log(data);

    });

    //if($("body").height()+60>$(window).height()){

        //$("html,body").animate({scrollTop:$("body").height()-$(window).height()+'px'},1000);

        //$("html,body").scrollTop($("body").height()-$(window).height()+60);

    //  console.log($("html,body").scrollTop());

    //}

}





String.stringFormat = function (str) {

    for (var i = 1; i < arguments.length; i++) {

        str = str.replace(new RegExp("\\{" + (i - 1) + "\\}", "g"), arguments[i] != undefined ? arguments[i] : "");

    }

    return str;

};



function popBigPic(id){

    layer.open({

        type: 1,

        content: '<img width="100%" onclick="layer.closeAll()" src="'+$(id).attr("src")+'">',

        style: 'width:auto; height:auto; color:#fff; border:none; text-align:center;max-width:100%;'

    });

}







    // $('.send-content').keydown(function(e){


    //         $(this)[0].scrollTop=$(this)[0].scrollHeight;

       

    // });







</script>

</html>